/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.model;

import com.google.appengine.api.datastore.Key;
import za.org.foobar.famon.util.DB;

import java.util.List;

/**
 * Base class for all model classes. Defines equals and hashcode to use the
 * primary key. This means you should not put newly created, non-persistent
 * instances into sets and maps etc as the hashcode will change once the
 * instances have been persisted.
 */
public abstract class ModelObject implements java.io.Serializable {
//    private static final Logger log = Logger.getLogger(getClass().getName());
    /**
     * Get the primary key of the object. This will be 0 if it is not
     * yet persistent.
     */
    public abstract Key getId();

    public boolean equals(Object obj) {
        Key id = getId();
        if (id == null) {
            return this == obj;
        }
        if (obj instanceof ModelObject) {
            return getClass() == obj.getClass()
                    && id == ((ModelObject)obj).getId();
        }
        return false;
    }

    public int hashCode() {
        Key id = getId();
        return id == null ? super.hashCode() : id.hashCode();
    }

    public String toString() {
        Key id = getId();
        return getClass().getSimpleName() + "-" + id;
    }

    public void delete() {
        //if (bDeleteSelf) {
//            log.info(getClass().getSimpleName() + ": Deleting: " + this);
        DB.remove(DB.merge(this));
        DB.closePM();
        //}
    }

    public static <T extends ModelObject> void deleteAll(List<T> list) {
        list.size(); //Need to get whole list to load.
        for (T mo : list) {
//            log.info(mo.getClass().getSimpleName() + ": Size1 = " + list.size());
//            log.info(mo.getClass().getSimpleName() + ": Removing: " + mo);
            mo.delete();
//            log.info(mo.getClass().getSimpleName() + ": Removed ");
//            log.info(mo.getClass().getSimpleName() + ": Size2 = " + list.size());
        }
    }
}
